import React from "react"
import { Form, Input, Button, message } from "antd"
import { post } from "@/utils/request"

interface LoginPostData {
  username: string
  password: string
}

export const LoginForm: React.FC = () => {
  const login = (data: LoginPostData) => {
    post("/pegasus/api/login/", data).then((res) => {
      if (res.status === 0) {
        // success
        message.success("登录成功")
        setTimeout(() => {
          window.location.href = "/home"
        }, 500)
      } else if (res.status === 4) {
        // password or username failed
        message.error("用户名或者密码错误")
      } else {
        message.error("服务器错误")
      }
    })
  }

  const handleFormFinish = (value: any) => {
    console.log(value)
    login(value)
  }

  return (
    <Form layout="vertical" onFinish={handleFormFinish}>
      <Form.Item
        label="用户名"
        name="username"
        rules={[{ required: true, message: "请输入用户名" }]}
      >
        <Input />
      </Form.Item>
      <Form.Item
        label="密码"
        name="password"
        rules={[{ required: true, message: "请输入密码" }]}
      >
        <Input type="password" />
      </Form.Item>
      <Form.Item>
        <Button type="primary" htmlType="submit" style={{ width: "100%" }}>
          登录
        </Button>
      </Form.Item>
    </Form>
  )
}
